package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.bean.CommemorateBean;
import flc.ast.bean.NoteBean;
import flc.ast.databinding.ActivityCommeDetailBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class CommeDetailActivity extends BaseAc<ActivityCommeDetailBinding> {

    public static int selPosition;
    private CommemorateBean commemorateBean;
    private Dialog myDeleteDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_comme_detail;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);

        mDataBinding.ivCommeDetailBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivDelete.setOnClickListener(this);
        mDataBinding.ivDownload.setOnClickListener(this);
        mDataBinding.ivBackground.setOnClickListener(this);
        mDataBinding.ivEdit.setOnClickListener(this);

        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDelete://删除
                myDeleteDialog.show();
                break;
            case R.id.ivDownload://下载
                saveImg();
                break;
            case R.id.ivBackground://封面
                getPermission();
                break;
            case R.id.ivEdit://编辑
                CommemorateActivity.commemorateBean = commemorateBean;
                CommemorateActivity.itemPosition = selPosition;
                startActivity(CommemorateActivity.class);
                break;
            //删除弹框
            case R.id.ivDialogDeleteCancel://取消
                myDeleteDialog.dismiss();
                break;
            case R.id.ivDialogDeleteRight://确认
                List<CommemorateBean> listSp = AppSpUtils.getCommemorateList();
                listSp.remove(selPosition);
                AppSpUtils.saveCommemorateList(listSp);
                myDeleteDialog.dismiss();
                finish();
                ToastUtils.showShort(getString(R.string.delete_suc));
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        setData();
    }

    private void setData() {
        List<CommemorateBean> listSp = AppSpUtils.getCommemorateList();
        commemorateBean = listSp.get(selPosition);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        long timeSpan = TimeUtils.getTimeSpan(commemorateBean.getDate(), TimeUtils.getNowString(format), format, TimeConstants.DAY);
        if (timeSpan < 0) {//小于0表示今年这天已经过了
            timeSpan = Math.abs(timeSpan);
            mDataBinding.tvTitle.setText(getString(R.string.past_text));
        } else {
            mDataBinding.tvTitle.setText(getString(R.string.remain_text));
        }
        mDataBinding.tvTitle.setText(commemorateBean.getTitle());
        if (commemorateBean.getPath().isEmpty()) {
            mDataBinding.rlCommemorateBg.setBackgroundColor(commemorateBean.getColor());
            mDataBinding.rlCommemorateImg.setVisibility(View.GONE);
        } else {
            mDataBinding.rlCommemorateBg.setBackgroundColor(0);
            mDataBinding.rlCommemorateImg.setVisibility(View.VISIBLE);
            Glide.with(mContext).load(commemorateBean.getPath()).into(mDataBinding.ivCommemorateImg);
        }
        mDataBinding.tvDate.setText(getString(R.string.target_date) + commemorateBean.getDate());
        mDataBinding.tvDay.setText(timeSpan + "");
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.rlCommemorateBg);
                        //保存到手机相册
                        File file = ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                    }
                });
            }
        }, 1000);
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getImage();
                    }
                }).request();
    }

    private void getImage() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .minCount(1)
                .maxCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        ArrayList<String> pathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            pathList.add(entity.getTargetPath());
                        }
                        List<CommemorateBean> listSp = AppSpUtils.getCommemorateList();
                        listSp.get(selPosition).setPath(pathList.get(0));
                        AppSpUtils.saveCommemorateList(listSp);
                        setData();
                    }
                });
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        ImageView dialogRight = inflate.findViewById(R.id.ivDialogDeleteRight);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        tip.setText(getString(R.string.is_delete_commemorate));
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
    }

}